// DOM元素
const passwordField = document.getElementById('password-field');
const lengthSlider = document.getElementById('password-length');
const lengthValue = document.getElementById('length-value');
const uppercaseCheckbox = document.getElementById('uppercase');
const lowercaseCheckbox = document.getElementById('lowercase');
const numbersCheckbox = document.getElementById('numbers');
const symbolsCheckbox = document.getElementById('symbols');
const excludeSimilarCheckbox = document.getElementById('exclude-similar');
const excludeDuplicateCheckbox = document.getElementById('exclude-duplicate');
const excludeSpaceCheckbox = document.getElementById('exclude-space');
const generateBtn = document.getElementById('generate-btn');
const copyBtn = document.getElementById('copy-btn');
const strengthValue = document.getElementById('strength-value');

// 字符集
const UPPERCASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const LOWERCASE_CHARS = 'abcdefghijklmnopqrstuvwxyz';
const NUMBER_CHARS = '0123456789';
const SYMBOL_CHARS = '!@#$%^&*()_+-=[]{}|;:,.<>?/';
const SPACE_CHAR = ' ';
const SIMILAR_CHARS = 'iIlL1oO0';

// 事件监听器
lengthSlider.addEventListener('input', updateLengthValue);
generateBtn.addEventListener('click', generatePassword);
copyBtn.addEventListener('click', copyPassword);

// 页面加载时生成初始密码
document.addEventListener('DOMContentLoaded', generatePassword);

// 更新长度值显示
function updateLengthValue() {
    lengthValue.textContent = lengthSlider.value;
}

// 生成密码
function generatePassword() {
    // 获取所有选项
    const length = parseInt(lengthSlider.value);
    const useUppercase = uppercaseCheckbox.checked;
    const useLowercase = lowercaseCheckbox.checked;
    const useNumbers = numbersCheckbox.checked;
    const useSymbols = symbolsCheckbox.checked;
    const excludeSimilar = excludeSimilarCheckbox.checked;
    const excludeDuplicate = excludeDuplicateCheckbox.checked;
    const excludeSpace = excludeSpaceCheckbox.checked;
    
    // 验证至少选择了一种字符类型
    if (!useUppercase && !useLowercase && !useNumbers && !useSymbols) {
        alert('请至少选择一种字符类型（大写字母、小写字母、数字或特殊符号）');
        return;
    }
    
    // 创建字符集
    let chars = '';
    
    if (useUppercase) chars += UPPERCASE_CHARS;
    if (useLowercase) chars += LOWERCASE_CHARS;
    if (useNumbers) chars += NUMBER_CHARS;
    if (useSymbols) chars += SYMBOL_CHARS;
    if (!excludeSpace) chars += SPACE_CHAR;
    
    // 排除相似字符
    if (excludeSimilar) {
        for (const char of SIMILAR_CHARS) {
            chars = chars.replace(new RegExp(char, 'g'), '');
        }
    }
    
    // 验证字符集不为空
    if (chars.length === 0) {
        alert('根据您的设置，没有可用的字符');
        return;
    }
    
    // 生成密码
    let password = '';
    let charArray = chars.split('');
    
    if (excludeDuplicate) {
        // 如果排除重复字符，并且长度超过可用字符数量
        if (length > charArray.length) {
            alert(`设置了排除重复字符，但密码长度(${length})超过了可用字符数量(${charArray.length})`);
            return;
        }
        
        // 随机选择不重复的字符
        const shuffled = [...charArray].sort(() => 0.5 - Math.random());
        password = shuffled.slice(0, length).join('');
    } else {
        // 随机选择可能重复的字符
        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * charArray.length);
            password += charArray[randomIndex];
        }
    }
    
    // 确保密码包含所选的所有字符类型
    const containsUppercase = useUppercase ? /[A-Z]/.test(password) : true;
    const containsLowercase = useLowercase ? /[a-z]/.test(password) : true;
    const containsNumbers = useNumbers ? /[0-9]/.test(password) : true;
    const containsSymbols = useSymbols ? new RegExp(`[${SYMBOL_CHARS.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')}]`).test(password) : true;
    
    // 如果不满足条件，重新生成
    if (!containsUppercase || !containsLowercase || !containsNumbers || !containsSymbols) {
        generatePassword();
        return;
    }
    
    // 更新密码显示
    passwordField.value = password;
    
    // 评估密码强度
    evaluatePasswordStrength(password);
}

// 评估密码强度
function evaluatePasswordStrength(password) {
    // 简单的密码强度评估
    let strength = 0;
    
    // 长度得分 (最高 5 分)
    if (password.length >= 8) strength += 1;
    if (password.length >= 12) strength += 1;
    if (password.length >= 16) strength += 1;
    if (password.length >= 20) strength += 1;
    if (password.length >= 24) strength += 1;
    
    // 字符类型得分 (每种类型 1 分，最高 4 分)
    if (/[a-z]/.test(password)) strength += 1;
    if (/[A-Z]/.test(password)) strength += 1;
    if (/[0-9]/.test(password)) strength += 1;
    if (/[^a-zA-Z0-9\s]/.test(password)) strength += 1;
    
    // 清除所有强度类
    strengthValue.classList.remove('weak', 'medium', 'strong', 'very-strong');
    
    // 根据得分设置强度级别
    if (strength <= 4) {
        strengthValue.textContent = '弱';
        strengthValue.classList.add('weak');
    } else if (strength <= 6) {
        strengthValue.textContent = '中等';
        strengthValue.classList.add('medium');
    } else if (strength <= 8) {
        strengthValue.textContent = '强';
        strengthValue.classList.add('strong');
    } else {
        strengthValue.textContent = '非常强';
        strengthValue.classList.add('very-strong');
    }
}

// 复制密码到剪贴板
function copyPassword() {
    const password = passwordField.value;
    
    if (!password) {
        alert('没有生成密码');
        return;
    }
    
    // 复制到剪贴板
    passwordField.select();
    document.execCommand('copy');
    
    // 通知用户
    alert('密码已复制到剪贴板');
    
    // 取消选择
    window.getSelection().removeAllRanges();
} 